//路由鉴权
import router from './router'
import nprogress from 'nprogress'
import pinia from './store'
import useUserStore from './store/modules/user'
import setting from './setting'
let userStore = useUserStore(pinia)

//全局前置守卫
router.beforeEach(async (to, from, next) => {
  document.title = `${to.meta.title} - ${setting.title}`
  //to 将要访问哪个路由
  // from 从哪个路由而来
  // next 路由放行函数
  nprogress.start() //进度条开始
  let token = userStore.token
  if (token) {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      //如果用户登录了，还想去登录页，则定向到首页
      if (userStore.userName) {
        next()
      } else {
        try {
          //获取用户信息
          await userStore.getUserInfo()
          next()
        } catch (error) {
          //退出登录
          await userStore.logout()
          //跳转到登录页
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

//全局后置守卫
router.afterEach((to, from) => {
  //to 将要访问哪个路由
  // from 从哪个路由而来
  nprogress.done() //进度条结束
})
